package com.cjm.algorithm.tree;

import com.cjm.algorithm.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class PreorderTraversal144 {
    public List<Integer> preorderTraversal(TreeNode root) {
        return m1(root, new ArrayList<Integer>());
    }

    public List<Integer> m3(TreeNode root) {
        // 这里指的是迭代法
        if (root == null) {
            return new ArrayList<>(0);
        }
        LinkedList<TreeNode> contain = new LinkedList<>();
        contain.add(root);
        // 这里是一个前序遍历， 所以顺序为 中 -> 左 -> 右
        // 所以放到容器里的顺序为 右 -> 左
        List<Integer> res = new ArrayList<>();
        while (!contain.isEmpty()) {
            TreeNode treeNode = contain.pollFirst();
            if (treeNode == null) {
                continue;
            }
            res.add(treeNode.val);
            if (treeNode.right != null) contain.addFirst(treeNode.right);
            if (treeNode.left != null) contain.addFirst(treeNode.left);
        }
        return res;
    }

    public List<Integer> m2(TreeNode root, List<Integer> res) {
        if (root==null) {
            return res;
        }
        res.add(root.val);
        m2(root.left, res);
        m2(root.right, res);
        return res;
    }

    private List<Integer> m1(TreeNode root, ArrayList<Integer> res) {
        if (root == null) {
            return res;
        }
        res.add(root.val);
        m1(root.left, res);
        m1(root.right, res);
        return res;
    }
}
